package com.yeswater.multithread.chapter1.test1_2.test1_2_8;

import org.junit.Test;

/**
 * author : yeswater
 * date : 2023/10/18
 *
 * -- , ++ 会出现线程安全问题
 * 1. 取得原有的值
 * 2. 计算 i--
 * 3. 对 i 重新赋值
 */

public class Run {

    /** 不共享数据的情况
     * count by A: count = 2
     * count by B: count = 2
     * count by C: count = 2
     * count by C: count = 1
     * count by C: count = 0
     * count by B: count = 1
     * count by B: count = 0
     * count by A: count = 1
     * count by A: count = 0
     */
    @Test
    public void test1(){
        MyThread a = new MyThread("A");
        MyThread b = new MyThread("B");
        MyThread c = new MyThread("C");
        a.start();
        b.start();
        c.start();
    }

    // 共享数据的情况
    @Test
    public void test2(){
        MyThread1 myThread = new MyThread1();
        Thread a = new Thread(myThread,"A");
        Thread b = new Thread(myThread,"B");
        Thread c = new Thread(myThread,"C");
        Thread d = new Thread(myThread,"D");
        Thread e = new Thread(myThread,"E");
        a.start();
        b.start();
        c.start();
        d.start();
        e.start();
    }

    @Test
    // 共享数据的情况
    public void test3(){
        MyThread2 myThread = new MyThread2();
        Thread a = new Thread(myThread,"A");
        Thread b = new Thread(myThread,"B");
        Thread c = new Thread(myThread,"C");
        Thread d = new Thread(myThread,"D");
        Thread e = new Thread(myThread,"E");
        a.start();
        b.start();
        c.start();
        d.start();
        e.start();
    }

    // synchronized 共享数据的情况
    @Test
    public void test4(){
        MyThread3 myThread = new MyThread3();
        Thread a = new Thread(myThread,"A");
        Thread b = new Thread(myThread,"B");
        Thread c = new Thread(myThread,"C");
        Thread d = new Thread(myThread,"D");
        Thread e = new Thread(myThread,"E");
        a.start();
        b.start();
        c.start();
        d.start();
        e.start();
    }

    // volatile 共享数据的情况

    /** 会出现问题 volatile 要配合原子操作??
     * count by A: count = 3
     * count by C: count = 2
     * count by B: count = 3
     * count by D: count = 1
     * count by E: count = 0
     */
    @Test
    public void test5(){
        MyThread4 myThread = new MyThread4();
        Thread a = new Thread(myThread,"A");
        Thread b = new Thread(myThread,"B");
        Thread c = new Thread(myThread,"C");
        Thread d = new Thread(myThread,"D");
        Thread e = new Thread(myThread,"E");
        a.start();
        b.start();
        c.start();
        d.start();
        e.start();
    }
}
